package LeetCode;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LC_592_FractionAdditionandSubtraction {

    public static void main(String[] args) {

    }

    class Solution {
        public String fractionAddition(String expression) {
            if (expression == null || expression.length() == 0) return expression;
            expression = expression.replace("-", "+-");
            String[] factors = expression.split("\\+");
            List<Integer> numerators = new ArrayList<>();
            List<Integer> denominators = new ArrayList<>();

            for (String factor : factors) {
                if ("".equals(factor)) continue;
                String[] numbers = factor.split("/");
                numerators.add(Integer.valueOf(numbers[0]));
                denominators.add(Integer.valueOf(numbers[1]));
            }

            int denominator = 1;
            for (int value : denominators) denominator *= value;
            int numerator = 0;
            for (int i = 0; i < numerators.size(); i++) {
                numerator += numerators.get(i) * (denominator / denominators.get(i));
            }
            int gcd = GCD(Math.abs(numerator), Math.abs(denominator));
            if (gcd == 0) return "-1";
            if (numerator > 0 && denominator < 0) {
                numerator = -numerator;
                denominator = -denominator;
            }
            return numerator / gcd + "/" + denominator / gcd;
        }

        private int GCD(int numerator, int denominator) {
            if (denominator == 0) return numerator;
            return GCD(denominator, numerator % denominator);
        }
    }

    class Solution_2 {
        public class Solution {
            int gcd(int x, int y) {
                return y == 0 ? Math.abs(x) : gcd(y, x % y);
            }

            public String fractionAddition(String expression) {
                Scanner sc = new Scanner(expression).useDelimiter("/|(?=[+-])");
                int numerator = 0, denominator = 1;
                while (sc.hasNext()) {
                    int a = sc.nextInt(), b = sc.nextInt();
                    numerator = numerator * b + denominator * a;
                    denominator *= b;
                    int g = gcd(denominator, numerator);
                    numerator /= g;
                    denominator /= g;
                }
                return numerator + "/" + denominator;
            }

        }
    }
}